package com.lokiy.kit.widget

import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.DrawableWrapper

/**
 *
 * @author Lokiy
 * @date 2023-10-23 16:39
 */
class ClipBoundDrawable(dr: Drawable) : DrawableWrapper(dr) {

    private val clipBounds: Rect = Rect()

    fun setClipBounds(left: Int, top: Int, right: Int, bottom: Int) {
        clipBounds.set(left, top, right, bottom)
        invalidateSelf()
    }

    override fun draw(canvas: Canvas) {
        val dr = drawable ?: return

        if (clipBounds.width() == 0) {
            clipBounds.set(bounds)
        }
        val bounds = bounds

        if (bounds.width() > 0 && bounds.height() > 0) {
            canvas.save()
            canvas.clipRect(clipBounds)
            dr.draw(canvas)
            canvas.restore()
        }
    }
}